package Expense;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.Timer;

import Login.Button;
import Login.DBHandler;
import Login.MainFrame;

public class ExpensePane extends JPanel implements ActionListener, MouseMotionListener, MouseListener, ItemListener, FocusListener, KeyListener{
	private DBHandler db;
	private JPanel parent;
	private CardLayout cards;
	private BufferedImage bg, panel1, panel2, panel2a, panel3;
	private JFrame frame;
	private int userType, curPanel;
	private String error;
	private Button salesBtn, inBtn, expBtn, usBtn, logBtn, viewExp, manageExp, expTime;
	private Timer time;
	private JComboBox dayBox, yearBox, monthBox;
	private JTextField rowBox, textBox, costBox, totalBox;
	private Date date;
	private JLabel d, m, y, cost, name, total;
	private JLabel day, month, year, row;
	private JButton prevDay, prevRow, nextDay, nextRow, addBtn;
	private JPanel recordPane;
	private ArrayList<Expense> expenses;
	private JScrollPane scrollPane;
	private ArrayList<JLabel> indexes;
	private ArrayList<JTextField>costBoxes,comments;
	private int batchMark;
	private String CurrentText;
	
	public ExpensePane(DBHandler db, JPanel parent, CardLayout cards, BufferedImage bg, JFrame frame, int userType){
		this.db=db;
		this.parent=parent;
		this.cards=cards;
		this.bg=bg;
		this.frame=frame;
		this.userType=userType;
		this.setLayout(null);
		error="";	
		date=new Date();
		day = new JLabel("Day :");
		month = new JLabel("Month :");
		year = new JLabel("Year :");
		row = new JLabel("Row :");
		d=new JLabel(date.getDate()+"");
		cost = new JLabel("Amount:");
		name = new JLabel("Name:");
		total = new JLabel("Total: ");
		addBtn= new JButton("Add");
		
		String s="";
		switch(date.getMonth()){
			case 0: s="January"; break;
			case 1: s="February"; break;
			case 2: s="March"; break;
			case 3: s="April"; break;
			case 4: s="May"; break;
			case 5: s="June"; break;
			case 6: s="July"; break;
			case 7: s="August"; break;
			case 8: s="September"; break;
			case 9: s="October"; break;
			case 10: s="November"; break;
			case 11: s="December"; break;
		}
		m=new JLabel(s);
		y=new JLabel((date.getYear()+1900)+"");
		
		dayBox=new JComboBox();
		monthBox=new JComboBox();
		yearBox=new JComboBox();
		rowBox = new JTextField();
		textBox = new JTextField();
		costBox = new JTextField();
		
		prevDay=new JButton("Previous Day");
		prevRow= new JButton("Previous Row");
		nextDay= new JButton("Next Day");
		nextRow= new JButton("Next Row");
		
		totalBox=new JTextField("");
        
		
		dayBox.setBounds(280, 185, 45, dayBox.getPreferredSize().height);
		monthBox.setBounds(375, 185, 100, monthBox.getPreferredSize().height);
		yearBox.setBounds(523, 185, 70, yearBox.getPreferredSize().height);
		day.setBounds(248, 169, 50, 50);
		month.setBounds(335, 169, 70, 50);
		year.setBounds(475, 169, 70, 50);
		row.setBounds(335, 225, 50, 25);
		rowBox.setBounds(380, 227, 90, 26);
		d.setBounds(298, 187, 50, d.getPreferredSize().height);
		m.setBounds(385, 187, 100, m.getPreferredSize().height);
		y.setBounds(523, 187, 50, y.getPreferredSize().height);
		totalBox.setBounds(505, 450, 175, 20);
		total.setBounds(470, 450, 50, 20);
		totalBox.setVisible(false);
		total.setVisible(false);
		
		prevDay.setBounds(135, 185, prevDay.getPreferredSize().width,
				prevDay.getPreferredSize().height);
		prevRow.setBounds(205, 225, prevRow.getPreferredSize().width,
				prevRow.getPreferredSize().height);
		nextDay.setBounds(615, 185, nextDay.getPreferredSize().width,
				nextDay.getPreferredSize().height);
		nextRow.setBounds(510, 225, nextRow.getPreferredSize().width,
				nextRow.getPreferredSize().height);
		name.setBounds(161, 425, 50, name.getPreferredSize().height);
		cost.setBounds(441, 425, 50, cost.getPreferredSize().height);
		textBox.setBounds(210, 423, 180, textBox.getPreferredSize().height);
		costBox.setBounds(495, 423, 180, costBox.getPreferredSize().height);
		addBtn.setBounds(381, 450, 70, 30);
		
		Font font2 = new Font("Calibri", Font.PLAIN, 15); 
		dayBox.setFont(font2);
		monthBox.setFont(font2);
		yearBox.setFont(font2);
		d.setFont(font2);
		m.setFont(font2);
		y.setFont(font2);
		

		try{
			setComboBoxItems(monthBox);
			setComboBoxItems(yearBox);
		} catch(SQLException SqlEx){}
		
		this.add(dayBox);
		this.add(day);
		this.add(monthBox);
		this.add(month);
		this.add(yearBox);
		this.add(year);
		this.add(row);
		this.add(rowBox);
		this.add(prevDay);
		this.add(prevRow);
		this.add(nextDay);
		this.add(nextRow);
		this.add(textBox);
		this.add(costBox);
		this.add(d);
		this.add(m);
		this.add(y);
		this.add(cost);
		this.add(name);
		this.add(addBtn);
		this.add(totalBox);
		this.add(total);
		
		setInComponents(true);
		time= new Timer(300, this);
		error="";	
		curPanel=0;
		showButtons();
		viewExp.setCurImg(1);
		
		time = new Timer(300, this);
		this.addMouseListener(this);
		this.addMouseMotionListener(this);
		
		dayBox.addItemListener(this);
		monthBox.addItemListener(this);
		yearBox.addItemListener(this);
		textBox.addFocusListener(this);
		costBox.addFocusListener(this);
		rowBox.addFocusListener(this);
		recordPane=new JPanel();
		
		scrollPane=new JScrollPane(recordPane);
		scrollPane.setBounds(150, 261, 550, 180);
		
		this.add(scrollPane);
		
	
		setRecords("now()");
		if(expenses.isEmpty()){
			rowBox.setText("0");
			rowChange(0);
			error="*Error: No expenses recorded today";
			
		}
		else rowBox.setText(expenses.size()+"");
		recordPaneConfig();

		addBtn.setEnabled(false);
		addBtn.addActionListener(this);
		nextDay.addActionListener(this);
		prevDay.addActionListener(this);
		nextRow.addActionListener(this);
		prevRow.addActionListener(this);
		rowBox.addKeyListener(this);
		textBox.addKeyListener(this);
		costBox.addKeyListener(this);
		
		setEditable(false);
	}
	private void recordPaneConfig(){
		costBoxes=new ArrayList<JTextField>();
		comments=new ArrayList<JTextField>();
		indexes=new ArrayList<JLabel>();
		
		error = "";
		recordPane.removeAll();
		recordPane.setLayout(new GridLayout(expenses.size()+1, 3));
		if(curPanel!=2)
					recordPane.add(new JLabel("Number",JLabel.RIGHT));
						else	recordPane.add(new JLabel("Recorded on",JLabel.LEFT));recordPane.add(new JLabel("Expense"));
		recordPane.add(new JLabel("Cost"));
		if(expenses.size()>0)	
			for(int ctr=0;ctr<expenses.size();ctr++){
				indexes.add(new JLabel(""+(ctr+1),JLabel.RIGHT));
				comments.add(new JTextField(expenses.get(ctr).getComment()));
				costBoxes.add(new JTextField(expenses.get(ctr).getCost()+""));
				
				if(curPanel!=2){
					 						indexes.add(new JLabel(""+(ctr+1),JLabel.RIGHT));
					 						
					 						
					 						comments.get(ctr).setEditable(false);
					 						costBoxes.get(ctr).setEditable(false);
					 					}
					 					else	{
					 						indexes.add(new JLabel(expenses.get(ctr).getID(),JLabel.LEFT));
					 						comments.get(ctr).setEditable(false);
					 						costBoxes.get(ctr).setEditable(false);
					 					}
					 	
				recordPane.add(indexes.get(ctr));
				recordPane.add(comments.get(ctr));
				recordPane.add(costBoxes.get(ctr));
				//comments.get(ctr).setEditable(edit);
				//costBoxes.get(ctr).setEditable(edit);
				totalBox.setText(""+sumOfExpense());
				
				comments.get(ctr).addFocusListener(this);
				costBoxes.get(ctr).addFocusListener(this);
				comments.get(ctr).addKeyListener(this);
				costBoxes.get(ctr).addKeyListener(this);
			}
		else {error ="*Error: No expenses Listed on this day";
	 			totalBox.setText("0");
	 		}
		}
	private void recordPaneConfig(int rows){
		int ctr;
		error="";
		costBoxes=new ArrayList<JTextField>();
		comments=new ArrayList<JTextField>();
		indexes=new ArrayList<JLabel>();
		
		recordPane.removeAll();
		if(rows>0&&expenses.size()>0){
		recordPane.setLayout(new GridLayout(rows+1, 3));
		recordPane.add(new JLabel("Number"));
		recordPane.add(new JLabel("Expense"));
		recordPane.add(new JLabel("cost"));
		for(ctr=0;ctr<expenses.size();ctr++){
			indexes.add(new JLabel(""+(ctr+1)));
			comments.add(new JTextField(expenses.get(ctr).getComment()));
			costBoxes.add(new JTextField(expenses.get(ctr).getCost()+""));
		}
		
		for(ctr=0;ctr<rows;ctr++){
			recordPane.add(indexes.get(ctr));
			recordPane.add(comments.get(ctr));
			recordPane.add(costBoxes.get(ctr));
			if(curPanel==0){
				comments.get(ctr).setEditable(true);
				costBoxes.get(ctr).setEditable(true);
			}
			else{
				comments.get(ctr).setEditable(false);
				costBoxes.get(ctr).setEditable(false);
			}
			comments.get(ctr).addFocusListener(this);
			costBoxes.get(ctr).addFocusListener(this);
			comments.get(ctr).addKeyListener(this);
			costBoxes.get(ctr).addKeyListener(this);
		}
		
		batchMark=ctr;
		}
		else error="*Error:No expenses Listed on this day";
	}
	
	 
	public void setEditable(boolean b){
		for (int ctr = 0; ctr < expenses.size(); ctr++) {
			comments.get(ctr).setEditable(b);
			costBoxes.get(ctr).setEditable(b);
		}
	}

	public void manageVisibility(){

		if(curPanel ==0){
			for(int ctr=0;ctr<expenses.size();ctr++){
				comments.get(ctr).setEditable(false);
				costBoxes.get(ctr).setEditable(false);
			}
		}
		else if(curPanel ==1){
			for(int ctr=0;ctr<expenses.size();ctr++){
				comments.get(ctr).setEditable(true);
				costBoxes.get(ctr).setEditable(true);
			}
		}
		
	}
	public void setInComponents(boolean b){
		
		dayBox.setVisible(b);
		monthBox.setVisible(b);
		yearBox.setVisible(b);
		d.setVisible(!b);
		m.setVisible(!b);
		y.setVisible(!b);
		
		prevDay.setVisible(b);
		nextDay.setVisible(b);
		
		name.setVisible(!b);
		cost.setVisible(!b);
		costBox.setVisible(!b);
		textBox.setVisible(!b);
		addBtn.setVisible(!b);
	}
	public void insert(){
		int i=db.MySQLInsert("INSERT INTO Expense values (now(),'"+costBox.getText()+"','"+textBox.getText()+"');");
		
		if(i>0){
			
			setRecords("now()");
			//recordPaneConfig(Integer.valueOf(rowBox.getText()));
			paintAncestors(recordPane);
			costBox.setText("0");
			textBox.setText("");
			addBtn.setEnabled(false);
			recordPaneConfig();
			rowBox.setText(""+expenses.size());
			
		}
		scrollPane.revalidate();
	}
	
	public void setRecords(String s){
		expenses=new ArrayList<Expense>();
		ResultSet RS;
		
		if(s.endsWith("()"))
			RS=db.MySQLSelect("SELECT * from Expense where Date(ExpenseTime)=Date("+s+");");
		else RS=db.MySQLSelect("SELECT * from Expense where Date(ExpenseTime)='"+s+"';");
		
		try{
			while(RS.next())
				expenses.add(new Expense(RS.getString(1),RS.getString(3),RS.getDouble(2)));
			RS.close();
			error="";
		}catch (SQLException SQLe) {
			// TODO Auto-generated catch block
			error="*Error: Error in Collecting data";
		}
		
	}

	public void getMonthlyexpenses(int m){
		 			expenses=new ArrayList<Expense>();
		 			ResultSet RS;
		 	
		 			RS=db.MySQLSelect("SELECT * from Expense where Month(ExpenseTime)='"+m+"';");
		 			try{
		 				while(RS.next())
		 					expenses.add(new Expense(RS.getString(1),RS.getString(3),RS.getDouble(2)));
		 	
		 				RS.close();
		 			}catch (SQLException SQLe) {
		 				// TODO Auto-generated catch block
		 				error = "*Error: Error in collecting data";
		 			}
		 		}
	public void setupMonthlyReport(){
	 	
			
			getMonthlyexpenses(monthBox.getSelectedIndex()+1);
	
			recordPaneConfig();
			rowBox.setText(expenses.size()+"");
	
			for(int ctr=0;ctr<expenses.size();ctr++){
				comments.get(ctr).setEditable(false);
				costBoxes.get(ctr).setEditable(false);
	
			}
			paintAncestors(recordPane);
		}
	
	
	
	public void setComboBoxItems(JComboBox cb) throws SQLException{
		int limit,ctr;
		if(cb.getItemCount()>0)
			cb.removeAllItems();
		if(cb==monthBox){
			cb.addItem("January");cb.addItem("Febuary");cb.addItem("March");
			cb.addItem("April");cb.addItem("May");cb.addItem("June");
			cb.addItem("July");cb.addItem("August");cb.addItem("September");
			cb.addItem("October");cb.addItem("November");cb.addItem("December");
			
			ResultSet RS=db.MySQLSelect("Select Month(now());"),RY,RD;
			RS.first();
			cb.setSelectedIndex(RS.getInt(1)-1);
			
			RY=db.MySQLSelect("Select Year(now());");
			RY.first();
			
			
			
			if(RS.getInt(1)==1||RS.getInt(1)==3||RS.getInt(1)==5||RS.getInt(1)==7||RS.getInt(1)==8
					||RS.getInt(1)==10||RS.getInt(1)==12)
				limit=31;
			else if(RS.getInt(1)==2)
				if(RY.getInt(1)%4!=0)
					limit =28;
				else limit=29;
			else limit=30;
			
			for(ctr=1;ctr<=limit;ctr++)
				dayBox.addItem(""+ctr);
			RS.close();
			RY.close();
			
			
			RD=db.MySQLSelect("Select Day(now());");
			RD.first();
			
			dayBox.setSelectedItem(RD.getString(1));
			RD.close();
			
			}
		else if(cb==yearBox){
			ResultSet RS=db.MySQLSelect("Select Year(TimeRecorded) from Inventory group by year(TimeRecorded);");
			
			while(RS.next())
				cb.addItem(RS.getString(1));
			cb.setSelectedIndex(cb.getItemCount()-1);
			RS.close();
		}
		else if(cb==dayBox){
			if(monthBox.getSelectedIndex()==0||monthBox.getSelectedIndex()==2||monthBox.getSelectedIndex()==4||monthBox.getSelectedIndex()==6||
					monthBox.getSelectedIndex()==7||monthBox.getSelectedIndex()==9||monthBox.getSelectedIndex()==11)
				limit=31;
			else if(monthBox.getSelectedIndex()==1){
				if(Integer.valueOf(yearBox.getSelectedItem().toString())%4!=0)
					limit=28;
				else limit=29;
			}
			else limit=30;
			
			for(ctr=1;ctr<=limit;ctr++)
				dayBox.addItem(""+ctr);
		}
		
	}

	public void rowChange(int rows){
		error="";
		if(rows>expenses.size()){
			rows=expenses.size();
				
			error="*Error: Rows exceed number of records";
		}
		if(rows<0){
			rows=0;
			error = "*Error: Must have at least 0 row";
		}
		rowBox.setText(""+rows);
		recordPaneConfig(rows);
	}

	public double sumOfExpense(){
		 			double Total=0;
		 	
		 			for(int ctr=0;ctr<expenses.size();ctr++){
		 				Total+=expenses.get(ctr).getCost();
		 			}
		 			return Total;
		 		}
	
	//method that changes the dayBox based on the month
	public void dayBoxConfig(int month){
		int limit,year=Integer.valueOf(yearBox.getSelectedItem().toString()),MaxDay=dayBox.getItemCount(),Day=dayBox.getSelectedIndex()+1;
		//Determine month to determine number of days
		if(month==0||month==2||month==4||month==6||month==7||month==9||month==11)
			limit =31;
		else if(month==1)
			if(year%4!=0)
				limit =28;
			else limit=29;
		else limit=30;
		
		dayBox.removeItemListener(this);
		//dayBox.setSelectedIndex(0);
		
		if(MaxDay<limit)
			for(int ctr=MaxDay+1;ctr<=limit;ctr++)
				dayBox.addItem(""+ctr);
		else if(MaxDay>limit){
			dayBox.removeAllItems();
			for(int ctr=1;ctr<=limit;ctr++)
				dayBox.addItem(""+ctr);
			while(Day>limit)
				Day--;
			dayBox.setSelectedItem(""+Day);
		}
		monthBox.addItemListener(this);
		dayBox.addItemListener(this);
	}
	
	//Method that responds to the next and previous day buttons
	public void nextPrevDay(int change){
		int month;
		error="";
		if(change>0){
			if(dayBox.getSelectedIndex()<dayBox.getItemCount()-change)
				dayBox.setSelectedIndex(dayBox.getSelectedIndex()+change);
			else if(monthBox.getSelectedIndex()<monthBox.getItemCount()-change){
				monthBox.removeItemListener(this);
				monthBox.setSelectedIndex(monthBox.getSelectedIndex()+change);
				month=monthBox.getSelectedIndex();
				
				dayBoxConfig(month);
				
				
				dayBox.setSelectedIndex(0);
			}
			else{
				yearBox.removeItemListener(this);
				yearBox.addItem(""+(Integer.valueOf(yearBox.getSelectedItem().toString())+1));
				yearBox.setSelectedIndex(yearBox.getItemCount()-1);
				monthBox.setSelectedIndex(0);
				dayBox.setSelectedIndex(0);
				yearBox.addItemListener(this);
				
			}
			
		}
		else if(change<0){
			if(dayBox.getSelectedIndex()>0)
				dayBox.setSelectedIndex(dayBox.getSelectedIndex()+change);
			else if(monthBox.getSelectedIndex()>0){
				monthBox.removeItemListener(this);
				monthBox.setSelectedIndex(monthBox.getSelectedIndex()+change);
				month=monthBox.getSelectedIndex();
				dayBoxConfig(month);
				
				
				dayBox.setSelectedIndex(dayBox.getItemCount()-1);
			}
			else if(yearBox.getSelectedIndex()>0)
				yearBox.setSelectedIndex(yearBox.getSelectedIndex()+change);
			else error="*Error: No more record in the previous years";
		}
	}
	
	
	
	 public void showButtons(){
         try {
        	 switch(userType){
        	 case 4: 	salesBtn = new Button("images/b1.png", "images/b1a.png", "images/b1.png");
             			usBtn = new Button("images/b5.png", "images/b5a.png", "images/b5.png");
             			
        	 case 3: 	inBtn = new Button("images/b2.png", "images/b2a.png", "images/b2.png");
                 		expBtn = new Button("images/b3a.png", "images/b3.png", "images/b3.png");
                 		logBtn = new Button("images/b7.png", "images/b7a.png", "images/b7.png");
             }
             viewExp = new Button("images/e1.png", "images/e1a.png", "images/e1.png");
             manageExp = new Button("images/e2.png", "images/e2a.png", "images/e2.png");
             expTime = new Button("images/exp1.png", "images/exp1a.png", "images/exp1.png");
      		 panel1 = ImageIO.read(new File("images/viewexp.png"));
      		 panel2 = ImageIO.read(new File("images/manageExp.png"));
      		 panel2a = ImageIO.read(new File("images/newexpense.png"));
      		 panel3 = ImageIO.read(new File("images/expovertime.png"));
      		 
      		 /*
      		 prevDay = new Button("images/prev.png", "images/preva.png", "images/prev.png");
             prevRow = new Button("images/prevrow.png", "images/prevrowa.png", "images/prevrow.png");
             nextDay = new Button("images/nextday.png", "images/nextdaya.png", "images/nextday.png");
             nextRow = new Button("images/nextrow.png", "images/nextrowb.png", "images/nextrow.png");
              */
             if(userType==4)
            	 bg=ImageIO.read(new File("images/main2.png"));
             else
            	 bg=ImageIO.read(new File("images/main1.png"));
             
             
             
     } catch (IOException e) {
             System.out.print("Image not found");
             e.printStackTrace();
     }

     }
	@Override
	public void actionPerformed(ActionEvent AE) {
		// TODO Auto-generated method stub
		repaint();
		scrollPane.revalidate();
		switch(curPanel){
	
		case 0: viewExp.setCurImg(1);
				setEditable(false);
				break;
		case 1: manageExp.setCurImg(1);
				setEditable(true);break;
		case 2: expTime.setCurImg(1);
				setEditable(false);
		
		}
		if(AE.getSource()==addBtn)
			insert();
		
		else if(AE.getSource()==nextDay)
			nextPrevDay(1);
		
		else if(AE.getSource()==prevDay)
			nextPrevDay(-1);
		
			//DayBox.setSelectedIndex(DayBox.getSelectedIndex()-1);
		else if(AE.getSource()==nextRow)
			InfoBatches(true);
		
		else if(AE.getSource()==prevRow)
			InfoBatches(false);
		
		scrollPane.revalidate();
			
	}	
	public void paint(Graphics g){
		super.paint(g);
		Graphics2D g2D = (Graphics2D) g;
		time.start();
		g2D.drawImage(bg, 0, 0, null);
		switch(userType){
		case 4:		g2D.drawImage(usBtn.getCurImg(), 497, 8, null);
					g2D.drawImage(salesBtn.getCurImg(), 145, 8, null);
					g2D.drawImage(inBtn.getCurImg(), 269, 8, null);
					g2D.drawImage(expBtn.getCurImg(), 383, 8, null);
					break;
		case 3:		g2D.drawImage(inBtn.getCurImg(), 138, 8, null);
					g2D.drawImage(expBtn.getCurImg(), 243, 8, null);
		}

		g2D.drawImage(logBtn.getCurImg(), 611, 8, null);
		g2D.drawImage(viewExp.getCurImg(), 10, 135, null);
		g2D.drawImage(manageExp.getCurImg(), 10, 259, null);
		g2D.drawImage(expTime.getCurImg(), 10, 372, null);
		Font font = new Font("Calibri", Font.PLAIN, 20);
		
		g2D.setColor(Color.RED);
		g2D.setFont(font);
	
		if(curPanel==0){
			g2D.drawImage(panel1, 125, 105, null);
		}
		if(curPanel==1){
			g2D.drawImage(panel2, 125, 105, null);
			g2D.drawImage(panel2a, 125, 385, null);
					
	
		}
		if(curPanel==2){
			g2D.drawImage(panel3, 125, 105, null);
			
		}
		g2D.drawString(error, 297, 167);
		
		
	}
	@Override
	public void mouseClicked(MouseEvent m) {
		// TODO Auto-generated method stub
		
		switch(userType){
    	case 4:	if (m.getX() >= 504&& m.getX()<=581&&m.getY()>=7&&m.getY()<=85)//within the boundaries of us btn                       
    				cards.show(parent, "users");
				else if (m.getX() >= 275&& m.getX()<=354&&m.getY()>=7&&m.getY()<=88)//within the boundaries of inventory btn			
					cards.show(parent, "inventory");
				else if (m.getX() >= 151&& m.getX()<=229&&m.getY()>=8&&m.getY()<=86)//within the boundaries of sales btn			
					cards.show(parent, "sales");
				
    			break;
    	case 3:
    			if (m.getX() >= 143&& m.getX()<=223&&m.getY()>=7&&m.getY()<=86)//within the boundaries of inventory btn                       
    				cards.show(parent, "inventory");
				
    			break;
		}
			
		if (m.getX() >= 17&& m.getX()<=95&&m.getY()>=134&&m.getY()<=214){//within the boundaries of view btn			
			error  = "";
			viewExp.setCurImg(1);
			manageExp.setCurImg(0);
			expTime.setCurImg(0);
			
			curPanel=0;
			setInComponents(true);
			scrollPane.setBounds(150, 261, 550, 180);
			setEditable(false);
			scrollPane.revalidate();
			if(expenses.isEmpty()){
				rowBox.setText("0");
				rowChange(0);
				error="*Error: No expenses recorded today";
				
			}
			setRecords(yearBox.getSelectedItem().toString()+"-"+(monthBox.getSelectedIndex()+1)+"-"+dayBox.getSelectedItem().toString());
				manageVisibility();
				rowBox.setText(expenses.size()+"");
				recordPaneConfig();
		
			totalBox.setVisible(false);
			total.setVisible(false);
			scrollPane.setVisible(true);
			day.setVisible(true);
			year.setVisible(true);
		}
		else if (m.getX() >= 16&& m.getX()<=97&&m.getY()>=257&&m.getY()<=337){//within the boundaries of manage btn			
			error  = "";
			manageExp.setCurImg(1);
			viewExp.setCurImg(0);
			expTime.setCurImg(0);
			
			curPanel=1;
			setInComponents(false);
			total.setVisible(false);
			setRecords("now()");
			recordPaneConfig();
			rowBox.setText(expenses.size()+"");
			
			paintAncestors(recordPane);
			scrollPane.setBounds(150, 261, 550, 110);
			setEditable(true);
			scrollPane.revalidate();

			scrollPane.setVisible(true);
			day.setVisible(true);
			year.setVisible(true);
			totalBox.setVisible(false);
			manageVisibility();
			
		}
		else if (m.getX() >= 16&& m.getX()<=97&&m.getY()>=370&&m.getY()<=450){//within the boundaries of over time btn
			curPanel=2;
			expTime.setCurImg(1);
			viewExp.setCurImg(0);
			manageExp.setCurImg(0);
			setRecords(yearBox.getSelectedItem().toString()+"-"+(monthBox.getSelectedIndex()+1)+"-"+dayBox.getSelectedItem().toString());
				manageVisibility();
				rowBox.setText(expenses.size()+"");
				recordPaneConfig();
				total.setVisible(true);

				scrollPane.setBounds(150, 261, 550, 180);
			setEditable(false);
		//	scrollPane.setVisible(false);
			if(expenses.isEmpty()){
				rowBox.setText("0");
				rowChange(0);
				error="*Error: No expenses recorded today";
				
			}
			setupMonthlyReport();
			
			totalBox.setVisible(true);
			totalBox.setEditable(false);
			setInComponents(false);
			this.m.setVisible(false);
			this.d.setVisible(false);
			this.y.setVisible(false);
			this.day.setVisible(false);
			this.year.setVisible(false);
			
			monthBox.setVisible(true);
			name.setVisible(false);
			cost.setVisible(false);
			costBox.setVisible(false);
			textBox.setVisible(false);
			addBtn.setVisible(false);
			
			
		}

		if (m.getX() >= 617&& m.getX()<=698&&m.getY()>=9&&m.getY()<=85){//within the boundaries of log out btn                  
			final JFrame frame2  = new JFrame("Confirm Action");

    		JLabel label  = new JLabel();
    		JLabel label2 = new JLabel("Are you sure you want to log out?");
    		JButton yes = new JButton("Yes");
    		JButton no = new JButton("No");
    		yes.addActionListener(
    				new ActionListener(){
    					@Override
    					public void actionPerformed(ActionEvent arg0) {
    						// TODO Auto-generated method stub
    						new MainFrame();
    						frame.dispose();
    		                frame2.dispose();
    					}
    				}
    		);
    		yes.setIcon(new ImageIcon("Images/yes.png"));
    		no.setIcon(new ImageIcon("Images/no.png"));
    		
    		no.addActionListener(
    				new ActionListener(){
    					@Override
    					public void actionPerformed(ActionEvent arg0) {
    						// TODO Auto-generated method stub
    						frame2.dispose();
    					}
    				}
    		);
    		
    		label2.setFont(new Font(Font.SERIF, Font.PLAIN, 17));
    		
    		JPanel panel  = new JPanel();
    		ImageIcon confirm;
    		confirm= new ImageIcon("Images/confirmaction.png");
    		label.setIcon(confirm);
    		
    		panel.add(label);
    		panel.add(label2);
    		panel.add(yes);
    		panel.add(no);

    		label.setBounds(26, 20, 120, 120);
    		label2.setBounds(145, 40, 250, 30);
    		yes.setBounds(160, 105, 80, yes.getPreferredSize().height);
    		no.setBounds(260, 105, 80, no.getPreferredSize().height+2);
    		
    		panel.setLayout(null);
    		frame2.add(panel);
    		frame2.setVisible(true);
    		frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    		frame2.setSize(400, 200);
    		frame2.setLocationRelativeTo(null);
    	 	
    	}	   
        	
		

	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseDragged(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseMoved(MouseEvent m) {
		// TODO Auto-generated method stub
		switch(userType){
         
         case 4:
                 if (m.getX() >= 151&& m.getX()<=229&&m.getY()>=8&&m.getY()<=86)//within the boundaries of sales btn                     
                         salesBtn.setCurImg(1);
                 else if (m.getX() >= 275&& m.getX()<=354&&m.getY()>=7&&m.getY()<=88)//within the boundaries of inventory btn                    
                	 	 inBtn.setCurImg(1);
                 else if (m.getX() >= 504&& m.getX()<=581&&m.getY()>=7&&m.getY()<=85)//within the boundaries of us btn                   
                         usBtn.setCurImg(1);
                 else if (m.getX() >= 617&& m.getX()<=698&&m.getY()>=9&&m.getY()<=85)//within the boundaries of log out btn                      
                         logBtn.setCurImg(1);
         
                 else{
                         salesBtn.setCurImg(0);
                         inBtn.setCurImg(0);
                         usBtn.setCurImg(0);
                         logBtn.setCurImg(0);
                 }
                 break;
         case 3:
                 if (m.getX() >= 617&& m.getX()<=698&&m.getY()>=9&&m.getY()<=85)//within the boundaries of log out btn                      
                         logBtn.setCurImg(1);
                 else{
                         inBtn.setCurImg(0);
                         expBtn.setCurImg(0);
                         logBtn.setCurImg(0);
                 }
                 break;
		 }
		
			if (m.getX() >= 17&& m.getX()<=95&&m.getY()>=134&&m.getY()<=214)//within the boundaries of view btn			
				viewExp.setCurImg(1);
					
			else if (m.getX() >= 16&& m.getX()<=97&&m.getY()>=257&&m.getY()<=337)//within the boundaries of manage btn			
				manageExp.setCurImg(1);
			
			else if (m.getX() >= 16&& m.getX()<=97&&m.getY()>=370&&m.getY()<=450)//within the boundaries of over time btn
				expTime.setCurImg(1);
	
		 else{
			 
			 	viewExp.setCurImg(0);
			 	manageExp.setCurImg(0);
				expTime.setCurImg(0);
			
			 
		 }
	}
	private void InfoBatches(boolean next){
		int rows=Integer.valueOf(rowBox.getText()),i=0;
		
		if(next&&rows<expenses.size()){
			while(batchMark>=0&&batchMark+rows>expenses.size())
				batchMark--;
			//System.out.println("Batch: "+batchMark);
			if(batchMark+rows<=expenses.size()){
				for(int ctr=batchMark;ctr<rows+batchMark;ctr++){
					indexes.get(i).setText(""+(ctr+1));
					comments.get(i).setText(expenses.get(ctr).getComment());
					costBoxes.get(i).setText(expenses.get(ctr).getCost()+"");
					i++;
				}
				batchMark+=rows;
				
				for(int c=i;c<indexes.size();c++){
					indexes.get(i).setText("");
					comments.get(i).setText("");
					costBoxes.get(i).setText("");
					i++;
				}
			}
		//	System.out.println("B: "+batchMark);
		}
		else if(rows<expenses.size()){
			batchMark-=rows;
			while(batchMark-rows<0)
				batchMark++;
			if(batchMark-rows>=0){
				int ctr;
				i=rows;
				for(ctr=batchMark;ctr>=batchMark-rows;ctr--){
					indexes.get(i).setText(""+(ctr+1));
					comments.get(i).setText(expenses.get(ctr).getComment());
					costBoxes.get(i).setText(expenses.get(ctr).getCost()+"");
					i--;
				}
				//batchMark+=rows;
		//		System.out.println("BP: "+batchMark);
			}
			
		}
	}

	
	public void DeleteRecord(int i){
		
		try {
			db.MySQLUpdate("DELETE FROM Expense where ExpenseTime='"+expenses.get(i).getID()+"';");
			error="";
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			error="*Error: "+e;
		}
		expenses.remove(i);
		recordPaneConfig(Integer.valueOf(rowBox.getText())-1);
                rowBox.setText(""+(Integer.valueOf(rowBox.getText())-1));
		paintAncestors(recordPane);
	}
	
	
	public void paintAncestors(Container cn){
		Container C=cn;
		while(C.getParent()!=null){
			C.repaint();
			C=C.getParent();
		}
	}
	
	@Override
	public void itemStateChanged(ItemEvent IE) {
		if(IE.getSource()==monthBox){
			monthBox.removeItemListener(this);
			dayBoxConfig(monthBox.getSelectedIndex());
		}
		if(IE.getSource()==dayBox||IE.getSource()==monthBox||IE.getSource()==yearBox){
			setRecords(yearBox.getSelectedItem().toString()+"-"+(monthBox.getSelectedIndex()+1)+"-"+dayBox.getSelectedItem().toString());
			recordPaneConfig();
			rowBox.setText(expenses.size()+"");
			
			paintAncestors(recordPane);
		}
		else if(curPanel !=2&&IE.getSource()==monthBox)
				setupMonthlyReport();

			//TBL.changedDate(yearBox.getSelectedItem().toString()+"-"+monthBox.getSelectedIndex()+1+"-"+DayBox.getSelectedItem().toString());
	}

	@Override
	public void focusGained(FocusEvent FE) {
		int i;
		
		if(comments.contains(FE.getSource())){
			i=comments.indexOf(FE.getSource());
			CurrentText=comments.get(i).getText();
		}
		else if(costBoxes.contains(FE.getSource())){
			i=costBoxes.indexOf(FE.getSource());
			CurrentText=costBoxes.get(i).getText();
		}
		else if(FE.getSource()==textBox)
			CurrentText=textBox.getText();
		else if(FE.getSource()==costBox)
			CurrentText=costBox.getText();
		
		
		
	}

	@Override
	public void focusLost(FocusEvent FE) {
		int i;
		JTextField jText=null;
		
		error = "";
			if(comments.contains(FE.getSource())){
				try{
					i=comments.indexOf(FE.getSource());
					jText=comments.get(i);
					
					if(comments.get(i).getText().length()==0){
						error = "*Error: Do not put empty comments!";
						jText.setText(CurrentText);
					}
					else if(CurrentText!=comments.get(i).getText())
					
					db.MySQLUpdate("Update Expense SET Comment='"+comments.get(i).getText()+"' where ExpenseTime='"+expenses.get(i).getID()+"';");
					
				}catch(SQLException sqlEX){
				error = "*Error: "+sqlEX;
					if(jText!=null)
						jText.setText(CurrentText);
				}
			}
			else if(costBoxes.contains(FE.getSource())){
				double amt=0;
				i=costBoxes.indexOf(FE.getSource());
				try{
					amt=Double.valueOf(costBoxes.get(i).getText());
				}catch(NumberFormatException sqlEX){
					error = "*Error: Type numbers only!";
					costBoxes.get(i).setText(CurrentText);
					amt=expenses.get(i).getCost();
				}
					
					jText=costBoxes.get(i);
					
					
					
					
					if(costBoxes.get(i).getText().length()==0){
						error = "*Error: Do not leave the cost empty!";
						jText.setText(CurrentText);
					}
					else if(CurrentText!=costBoxes.get(i).getText())
						if(amt<0){
							 									amt*=-1;
							 									costBoxes.get(i).setText(""+amt);
							 									error ="*Error: Please type positive numbers";
							 								}
						try {
							db.MySQLUpdate("Update Expense SET Cost='"+amt+"' where ExpenseTime='"+expenses.get(i).getID()+"';");
							expenses.get(i).setCost(amt);
							totalBox.setText(""+sumOfExpense());
						} catch (SQLException e) {
						error = "*Error: Type numbers only!";
						}
			}
			
			else if(FE.getSource()==textBox||FE.getSource()==costBox){
				double amt=0;
				
				try{
					amt=Double.valueOf(costBox.getText());
				}catch(NumberFormatException NE){
					amt=0;
					costBox.setText(""+amt);
					error = "*Error: Amount must be in numbers";
				}
				
				if(textBox.getText().length()>0&&costBox.getText().length()>0&&amt>=0)
					addBtn.setEnabled(true);
				else addBtn.setEnabled(false);
			}
			else if(FE.getSource()==rowBox){
				try{
					if(Integer.valueOf(rowBox.getText())>0)
						rowChange(Integer.valueOf(rowBox.getText()));
					else if(Integer.valueOf(rowBox.getText())==0)
						error = "*Error: 0 rows dispalyed.";
					else {
						error = "*Error: No negative numbers";
						rowBox.setText(""+comments.size());
					}
				}catch(NumberFormatException NF){
					error = "*Error: Please enter a valid number";
					rowBox.setText(""+comments.size());
				}
			}
		
		CurrentText="";
	}


	@Override
	public void keyPressed(KeyEvent KE) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void keyReleased(KeyEvent KE) {
		int i;
		error = "";
		if(KE.getSource()==rowBox&&KE.getKeyCode()==KeyEvent.VK_ENTER){
		try{
			if(Integer.valueOf(rowBox.getText())>=0){
				rowChange(Integer.valueOf(rowBox.getText()));
				if(Integer.valueOf(rowBox.getText())==0)
					error ="*Error: 0 rows dispalyed.";
			}
			else {
				error ="*Error: No negative numbers";
				rowBox.setText(""+comments.size());
			}
		}catch(NumberFormatException NF){
			error ="*Error: Please enter a valid number";
			rowBox.setText(""+comments.size());
			}
		paintAncestors(recordPane);
		}
		else if(comments.contains(KE.getSource())&&KE.getKeyCode()==KeyEvent.VK_ENTER){
			i=comments.indexOf(KE.getSource());
			costBoxes.get(i).requestFocus();
		}
		else if(costBoxes.contains(KE.getSource())&&KE.getKeyCode()==KeyEvent.VK_ENTER){
			i=costBoxes.indexOf(KE.getSource());
			if(i<comments.size()-1)
				comments.get(i+1).requestFocus();
		}
		else if(KE.getSource()==textBox&&KE.getKeyCode()==KeyEvent.VK_ENTER)
			costBox.requestFocus();
		else if(KE.getSource()==costBox&&KE.getKeyCode()==KeyEvent.VK_ENTER){
			if(textBox.getText().length()>0)
				addBtn.requestFocus();
			else textBox.requestFocus();
		}
		else if(costBoxes.contains(KE.getSource())&&KE.getKeyCode()==KeyEvent.VK_DELETE)
			DeleteRecord(costBoxes.indexOf(KE.getSource()));
		else if(comments.contains(KE.getSource())&&KE.getKeyCode()==KeyEvent.VK_DELETE)
			DeleteRecord(comments.indexOf(KE.getSource()));
	}
	@Override
	public void keyTyped(KeyEvent KE) {
		// TODO Auto-generated method stub
		
	}
}
